import {
  BASE_URL
} from '../../../http/config';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    current: 0,
    titleList: ["课程详情", "课程列表", "名师介绍", "课堂交流", "课程评价"],
    classroomTitle:['最新发表','最后回复','回复数量'],
    questionResponse:[
      {img:"/images/@2x_user.png",title:"用户9527"},
      {img:"/images/@2x_time.png",title:"15分钟前"},
      {img:"/images/@2x_answer.png",title:"12"},
    ],
    // 课程详情数据
    userId:0,
    courseId:0,
    courseDetailData: {},
    buy:false,
    collection:false,
    indexFather:-1,
    collectNum:0,
    EvaluateNum:0,
    VideoList:{} ,
    // baseUrl: 'http://localhost:8080', //该课程下全部的视频
    currentVideo: null  ,//当前视频
    showVideo: false, // 是否显示视频
    evaluateList:{},
    TeacherId:0,
    consult: {},

  },
  navigateToAllReviews(){
    const { courseId, userId } = this.data;
   
    wx.navigateTo({
      url: `/course/pages/courseallevalute/courseallevalute?courseid=${courseId}`,
    })  
  }
  ,
  navigateToWriteEvaluate(){
    if (!this.data.buy) {
      wx.showToast({
        title: '请先购买课程后再评价',
        icon: 'none',
        duration: 1500
      });
      return; // 不跳转
    }
    const { courseId, userId } = this.data;
    wx.navigateTo({
      url: `/course/pages/coursewriteevaluate/coursewriteevaluate?courseid=${courseId}&userid=${userId}`,
    })

  },


  chooseItem(e) {
    console.log(e.target.dataset.index)
    this.setData({
      current: e.target.dataset.index
    })
  },
  // swiper的change事件函数
  swiperChanged(e) {
    // console.log(e.detail.current)
    this.setData({
      current: e.detail.current
    })
  },
  getCourseDetail(id) {
    console.log(id)
    wx.request({
      url: `${BASE_URL}/course?id=${id}`,
      method: 'GET',
      success: (res) => {
        console.log("课程详情数据：", res.data.data)
        this.setData({
          courseDetailData:res.data.data,
          TeacherId:res.data.data.consultId,

        }
        )
        this.getConsultDetail(this.data.consultId);
        console.log(this.data.TeacherId);
      },
      fail: (err) => {}
    })
  },
  getIsBuy(userId,courseId) {
    wx.request({
      url: `${BASE_URL}/courseOrder/all?courseid=${courseId}&userid=${userId}`,
      method: 'GET',
      success: (res) => {
        console.log("订单数据：", res.data.data)
        
        const hasOrder = res.data.data && res.data.data.total && res.data.data.total > 0;
      this.setData({
        buy: hasOrder // 如果total大于0，表示已购买，设置buy为true
      });
      },
      fail: (err) => {}
    })
  },
  
  buy(){
    if (!this.data.userId || this.data.userId === 0) {
      wx.showModal({
        title: '提示',
        content: '请先登录后再购买课程',
        confirmText: '去登录',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login' // 修改为你自己的登录页路径
            });
          }
        }
      });
      return; // 阻止后续执行
    }
    const orderData = {
      courseid: this.data.courseId,
      userid: this.data.userId,
      orderPrice: this.data.courseDetailData.newPrice,
      orderType:1  
    };
  
    wx.request({
      url: `${BASE_URL}/courseOrder`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: orderData,
      success: (res) => {
        console.log('订单创建成功:', res.data);
        if (res.data.code === 200) {
          wx.showToast({
            title: '购买成功',
            icon: 'success'
          });
          this.setData({
            buy: true
          });
         this.updateUserPoints();
          // 可选：刷新课程详情（更新学习数等）
          this.getCourseDetail(this.data.courseId);
        } else {
          wx.showToast({
            title: res.data.msg || '下单失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('订单创建失败:', err);
        wx.showToast({
          title: '下单失败',
          icon: 'none'
        });
      }
    });
  },
  changeCollection() {
    const newStatus = !this.data.collection;
  
    // 更新本地状态
    this.setData({
      collection: newStatus
    });
  
    // 调用接口更新收藏状态
    wx.request({
      url: `${BASE_URL}/courseCollect`,
      method: newStatus ? 'POST' : 'DELETE', // 收藏用POST，取消收藏用DELETE
      header: {
        'Content-Type': 'application/json'
      },
      data: {
        courseid: this.data.courseId,
        userid: this.data.userId
      },
      success: (res) => {
        console.log(newStatus ? '收藏成功' : '取消收藏成功', res);
        // 更新收藏数量（可选）
        this.getCollectNum(this.data.courseId);
      },
      fail: (err) => {
        console.error('收藏操作失败', err);
        // 请求失败时回滚状态
        this.setData({
          collection: !newStatus
        });
      }
    });
  }
,  
  lookResponse(e){
    let indexfather=e.target.dataset.indexfather
    console.log(indexfather)
    if(indexfather!=this.data.indexFather){
    this.setData({
      indexFather:indexfather
    })
  }else{
    this.setData({
      indexFather:-1
    })
    }
  },
  getCollectNum(courseid) {
    const that = this;
    wx.request({
      url: `${BASE_URL}/courseCollect?courseid=${courseid}`,
      method: 'GET',
    
      success(res) {
        console.log('请求成功', res.data);
        that.setData({
          collectNum:res.data.data

        })
        
        
      },
      fail(err) {
        console.error('请求失败', err);
       
      }
    });
  },
  // 获取评价次数
  getEvaluateNum(courseid){
   
    const that = this;
    wx.request({
      url: `${BASE_URL}/courseEvaluate/courseid?courseid=${courseid}`,
      method: 'GET',
      success(res) {
        console.log('请求成功', res.data);
        that.setData({
          EvaluateNum:res.data.data

        })
      },
        fail(err) {
          console.error('请求失败', err);
        }
      });


  },
  // 获取该课程下的全部视频
  Getvideo(courseid){
    
    const that = this;
    wx.request({
      url: `${BASE_URL}/courseVideo/courseid?courseid=${courseid}`,
      method: 'GET',
      success(res) {
      
        that.setData({
         VideoList:res.data.data,
         currentVideo: null
        })
        // console.log(that.data.VideoList)
        // console.log(that.data.currentVideo)
        
      },
        fail(err) {
          console.error('请求失败', err);
        }
      });

  },
  // 播放视频
  playVideo(e) {
    if (!this.data.buy) {
      wx.showToast({
        title: '请先购买课程',
        icon: 'none',
        duration: 2000
      });
      return;  // 阻止播放视频
    }
    const video = e.currentTarget.dataset.video;
    console.log('用户点击播放视频：', video);
    this.setData({
      currentVideo: video,
      showVideo: true
    });
  }
  ,
  // 课程是否收藏
  checkIfCollected(courseid, userid) {
    wx.request({
      url: `${BASE_URL}/courseCollect/exit`,
      method: 'GET',
      data: {
        courseid: courseid,
        userid: userid
      },
      success: (res) => {
        console.log('是否已收藏：', res.data);
        // 假设后端返回 true/false 或 1/0
        if(res.data.data>0){
          this.setData({
            collection: true  // 转为布尔值设置状态
          });

        }
        
      },
      fail: (err) => {
        console.error('检查收藏状态失败：', err);
      }
    });
  }
  ,
  getCourseEvaluateList() {
    wx.request({
      url: `${BASE_URL}/courseEvaluate/all`,
      method: 'GET',
      data: {
        courseid: this.data.courseId, // 当前课程 ID
        pageNum: 1,                    // 第 1 页
        pageSize: 4                    // 每页 4 条
      },
      success: (res) => {
        if (res.data.code === 200) {
          console.log(res.data.data.list);
          this.setData({
            evaluateList: res.data.data.list 
          });
        } else {
          wx.showToast({
            title: '获取评价失败',
            icon: 'none'
          });
        }
      },
    
    });
  }
,  
getConsultDetail() {
  // console.log(this.data.TeacherId);
  wx.request({
    url: `${BASE_URL}/consult/${this.data.TeacherId}`,
    method: 'GET',
    success: (res) => {
      // console.log(res.data);
      if (res.data && res.data.data) {
        this.setData({ consult: res.data.data });
        console.log(this.data.consult);
      } else {
        wx.showToast({ title: '数据不存在', icon: 'none' });
      }
    },
    fail: () => {
      wx.showToast({ title: '请求失败', icon: 'none' });
    }
  });
},
goToConsultDetail() {
  wx.navigateTo({
    url: `/course/pages/FacultyDetail/FacultyDetail?id=${this.data.TeacherId}`
  });
},

goToConsultOrder() {
  wx.navigateTo({
    url: `/pages/ConsultOrder/ConsultOrder?id=${this.data.TeacherId}`
  });
},
updateUserPoints(){
  wx.request({
    url: `${BASE_URL}/points`,
    method: 'PUT',
    header: {
      'Content-Type': 'application/json'
    },
    data: {
      user_id: this.data.userId,
      points: this.data.courseDetailData.newPrice
    },
    success(res) {
      console.log("更新成功：", res.data);
    },
    fail(err) {
      console.error("请求失败：", err);
    }
  });
}
,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let userInfo=wx.getStorageSync('userInfo');
    this.setData({
      userId:userInfo.id

    })

    this.setData({
      courseId: options.id  // 使用setData更新data中的courseId
    })
    console.log(this.data.userId,this.data.courseId);
    
    this.getIsBuy(this.data.userId,this.data.courseId);
    this.getCourseDetail(options.id);
    this.getCollectNum(options.id);
    this.getEvaluateNum(options.id);
    this.Getvideo(options.id);
    this.checkIfCollected(options.id,this.data.userId);
    this.getCourseEvaluateList();
   
    

},
// 增加学习次数
videoPlayHandler(e){

  const updateData = {
    id: this.data.courseId,         // 课程ID（必填，用于定位要更新的课程）
    studyNumber: 1        // 学习量（根据实际需求传递，通常每次播放+1）
  };

  wx.request({
    url: `${BASE_URL}/course`,
    method: 'PUT',
    header: {
      'Content-Type': 'application/json'  // 仅保留JSON格式声明，其他头信息可省略
    },
    data: updateData,  // 只传递id和studyNumber
    success: (res) => {
      console.log('学习量更新成功', res.data);
      if (res.data.code === 200) {
        // 成功后可刷新课程详情，更新页面显示的学习次数
        this.getCourseDetail(this.data.courseId);
      }
    },
    fail: (err) => {
      console.error('学习量更新失败', err);
    }
  });


}

,
/**
 * 生命周期函数--监听页面初次渲染完成
 */
onReady() {

},

/**
 * 生命周期函数--监听页面显示
 */
onShow() {
  this.getEvaluateNum(this.data.courseId);
  this.getCourseEvaluateList();


},

/**
 * 生命周期函数--监听页面隐藏
 */
onHide() {

},

/**
 * 生命周期函数--监听页面卸载
 */
onUnload() {

},

/**
 * 页面相关事件处理函数--监听用户下拉动作
 */
onPullDownRefresh() {

},

/**
 * 页面上拉触底事件的处理函数
 */
onReachBottom() {

},

/**
 * 用户点击右上角分享
 */
onShareAppMessage() {

}
})